using System;
using System.Collections.Generic;
using System.Text;

using System.Xml;
using System.Net;
using System.IO;
using System.Reflection;

namespace GSN.VersionCheck
{
    class VersionChecker
    {
        static private string versionXml = "http://gsn.kipmi.com/version.xml";

        static public void check(IVersionCheckDisplay display)
        {
            try
            {
                Logger.log("Starting new version check.");

                WebRequest req = WebRequest.Create(versionXml);
                req.Proxy = WebRequest.GetSystemWebProxy();

                WebResponse resp = req.GetResponse();
                Stream respStream = resp.GetResponseStream();

                XmlDocument doc = new XmlDocument();
                doc.Load(respStream);

                respStream.Close();
                resp.Close();

                XmlNode latestVersionNode = doc.SelectSingleNode("GSN/Latest_Version");
                if (latestVersionNode == null)
                    return;

                Version latestVersion = new Version(latestVersionNode.InnerText);
                Version currentVersion = Assembly.GetExecutingAssembly().GetName().Version;

                if (latestVersion.CompareTo(currentVersion) > 0)
                {
                    // new version available
                    Logger.log("New version detected.");

                    System.Windows.Forms.DialogResult res = System.Windows.Forms.MessageBox.Show(
                        string.Format("A new version of GSN ({0}) is available. Would you like to download it now?",
                            latestVersion.ToString()), "New Version Available",
                            System.Windows.Forms.MessageBoxButtons.YesNo,
                            System.Windows.Forms.MessageBoxIcon.Question);

                    if (res == System.Windows.Forms.DialogResult.Yes)
                    {
                        Utils.launchHomepage();
                    }

                }
                else
                {
                    Logger.log("Current version is latest.");
                    display.displayNoUpdate();
                }

            }
            catch (Exception ex)
            {
                display.displayException(ex);
            }
        }
    }
}
